<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form divClass" v-if="headerShow">
                <div>
                    <a-form size="small" :model="pageData" layout="inline">
                        <a-form-item label="程序号">
                            <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" v-model="pageData.programNumber"
                                @focus="focusSel" @search="handleSearch" @change="cxChange(pageData.programNumber)"
                                :loading1="loading" :filter-option="false" allow-search allow-clear>
                                <a-option v-for="item in pageData.cxNameList" :value="item.programNumber">
                                    {{ item.programNumber }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="程序名称" field="programName">
                            <a-input :style="{ width: '200px' }" v-model="pageData.programName" disabled
                                style="color:#4e5969 !important">
                                {{ pageData.programName }}
                            </a-input>
                        </a-form-item>
                        <a-form-item label="程序类型" field="programType">
                            <a-input :style="{ width: '200px' }" v-model="pageData.programType" disabled
                                style="color:#4e5969 !important">
                                {{ pageData.programType }}
                            </a-input>
                        </a-form-item>
                    </a-form>
                </div>
                <div class="my-tool-bar">
                    <Toolbar style="float:right" :items="['查询', '新增', '删除', '导出']" @add="addHandler" @del="deleteHandler"
                        @select="selectHandler" @export="exports">
                    </Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <template #pageTabel>
            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressDragLeaveHidesColumns="true"
                    :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                    :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc"
                    :localeText="localeText1" @columnResized="onColumnResized" @columnMoved="onColumnMoved"></AgGridVuesCopys>
            </a-spin>
        </template>
        <paginationCopys :page-size-options="pagingList1" :page-size="pagination.pageSize" :current="pagination.page"
            :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
            style="justify-content: center" />
        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" :mask-closable="false" :width="400"
            popup-container=".arco-tabs-content" height="100%" :visible="pageData.showAdd"
            :ok-loading="pageData.pageLoading" placement="bottom" unmountOnClose @ok="sideOk" @cancel="sideNo">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <a-tabs   :lazy-load="true">
                <a-form ref="formRef" layout="horizontal" :model="dataForm" size="small">
                    <a-space>
                        <a-form-item label-col-flex="80px" label="程序号" field="programNumber"
                            :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '程序号必填' }]">
                            <a-select popup-container="html"  :style="{ width: '200px' }" class="bacClass" v-model="dataForm.programNumber"
                                @focus="focusSel5" @search="handleSearch5" @change="numChange" :loading5="loading5"
                                allow-clear>
                                <a-option v-for="item in pageData.NumberList" :value="item.programNumber">
                                    {{ item.programNumber }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label-col-flex="80px" label="程序名称" field="programName"
                            :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '程序名称必填' }]">
                            <a-select popup-container="html"  :style="{ width: '200px' }" v-model="dataForm.programName" @focus="cxmcFocus2"
                                @change="cxChange2" allow-clear @click="cxClick2" disabled>
                                <a-option v-for="item in pageData.cxList" :value="item['programName']">
                                    {{ item["programName"] }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label-col-flex="80px" label="程序类型" field="programType"
                            :rules="[{ required: true, message: '程序类型必填' }]" :validate-trigger="['change', 'blur']">
                            <a-select popup-container="html"  :style="{ width: '200px' }" v-model="dataForm.programType" @focus="cxmcFocus2"
                                allow-clear @change="cxChange2" @click="cxClick2" disabled>
                                <a-option v-for="item in pageData.cxList" :value="item['programType']">
                                    {{ item["programType"] }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                    </a-space>
                </a-form>
            </a-tabs>
            <a-space>
                <Toolbar :items="['添加染化料信息', '删除', '复制']" @addyeing="addyeing" @del="deldyeling" @copy="copyPro"></Toolbar>
            </a-space>
            <a-table :style="{ marginTop: '10px' }" stripe :bordered="true" :scrollbar="true" sticky-header
                :columns="tableColumns1" :data="dataList" v-model:selected-keys="selectedRowKeys1" row-key="isTypeIds"
                :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }" size="mini" :pagination="false">
                <template #dyeProcessName="{ record }">
                    <a-select popup-container="html"  class="bacClass" v-model="record.dyeProcessName" @focus="focusSel1" @search="handleSearch1"
                        :loading1="loading1" allow-clear allow-search>
                        <a-option v-for="item in pageData.dyeNameList" :value="item">{{ item }}</a-option>
                    </a-select>
                </template>
                <template #thickenerStep="{ record }">
                    <a-input-number class="bacClass" v-model="record.thickenerStep" :min="0" :precision="0" />
                </template>
                <template #materialCode="{ record }">
                    <a-select popup-container="html"  class="bacClass" :loading="loading2" @search="handleSearch2" v-model="record.materialCode"
                        :filter-option="false" allow-search allow-clear @focus="focusSel2" @change="handCode(record)">
                        <a-option v-for="item in pageData.wlCodeList" :value="item['materialCode']">
                            {{ item["materialCode"] + ' —— ' + item["materialName"] }}
                        </a-option>
                    </a-select>
                </template>
                <template #materialName="{ record }">
                    <a-select popup-container="html"  class="bacClass" :loading="loading2s" @search="handleSearch2s" v-model="record.materialName"
                        :filter-option="false" allow-search allow-clear @focus="focusSel2s" @change="handName(record)">
                        <a-option v-for="item in pageData.wlNameList" :value="item['materialName']">
                            {{ item["materialName"] }}
                        </a-option>
                    </a-select>
                </template>
                <template #unit="{ record }">
                    <a-input v-model="record.unit" disabled></a-input>
                </template>
                <template #materialRatio="{ record }">
                    <a-input class="bacClass" v-model="record.materialRatio" />
                </template>
                <template #concentration="{ record }">
                    <a-input-number class="bacClass" v-model="record.concentration" :min="0" :precision="2" />
                </template>
                <template #concentrationUnit="{ record }">
                    <a-select popup-container="html"  class="bacClass" v-model="record.concentrationUnit" @focus="focusSel3" @search="handleSearch3"
                        :loading="loading3" allow-clear allow-search>
                        <a-option v-for="item in pageData.unitList" :value="item">{{ item }}</a-option>
                    </a-select>
                </template>
                <template #maxLimit="{ record }">
                    <a-input-number class="bacClass" v-model="record.maxLimit" :min="0" :precision="2" />
                </template>
                <template #operatingSteps="{ record }">
                    <a-select popup-container="html"  class="bacClass" v-model="record.operatingSteps" @focus="focusSel4" @search="handleSearch4"
                        :loading4="loading4" allow-clear allow-search>
                        <a-option v-for="item in pageData.stepList" :value="item">{{ item }}</a-option>
                    </a-select>
                </template>
                <template #chargingBasket="{ record }">
                    <a-input class="bacClass" v-model="record.chargingBasket" />
                </template>
                <template #coefficient="{ record }">
                    <a-input-number class="bacClass" v-model="record.coefficient" :min="0" :precision="0" />
                </template>
                <template #meansDelivery="{ record }">
                    <a-input class="bacClass" v-model="record.meansDelivery" />
                </template>
            </a-table>
        </a-drawer>
        <a-modal v-model:visible="visible" title="选择程序号复制" :draggable="true">
            <a-form-item label="程序号" style="padding-left:17%">
                <a-select popup-container="html"  class="bacClass" :style="{ width: '250px' }" v-model="dataForm.programId" @focus="focusSel7"
                    @search="handleSearch7" @change="copyCode" :loading7="loading7" :filter-option="false" allow-search
                    allow-clear>
                    <a-option v-for="item in pageData.cxIdList" :value="item.programName" :key="item.id">
                        {{ item.programName }}
                    </a-option>
                </a-select>
            </a-form-item>
            <template #footer>
                <a-button size="small" @click="visible = false">取消</a-button>
                <a-button type="primary" size="small" @click="handleSave">确认</a-button>
            </template>
        </a-modal>
        <a-modal v-model:visible="visible1" title="染化料详情" :width="1200" :footer="false" :draggable="true">
            <a-table :style="{
                height: '100%',
                marginTop: '10px',
            }" stripe :bordered="true" :scrollbar="true" sticky-header :columns="tableColumns1" :data="DetailList"
                size="mini">
            </a-table>
        </a-modal>
    </pageTabelLayout>
</template>

<script lang="ts">
import { pagingList } from "@/api/paging";
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { baseURL } from '../../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue';
import { AnyARecord } from 'dns';

import { localeText } from '@/api/aggridZw'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

interface BrandInfo {
    "id": any,
    "remark": string | undefined,
    "createName": string | undefined,
    "createTime": string | undefined,
    "updateName": string | undefined,
    "updateTime": string | undefined,
    "deleteState": any,
    "obsoleteState": any,
    "programNumber": any,
    "programType": any,
    "programName": any,
    "dyeProcessName": any,
    "thickenerStep": any,
    "materialCode": any,
    "materialName": any,
    "unit": any,
    "materialRatio": any,
    "concentration": any,
    "concentrationUnit": any,
    "maxLimit": any,
    "operatingSteps": any,
    "chargingBasket": any,
    "coefficient": any,
    "meansDelivery": any,
    "stepName": any,
    "programId": any,
}

export default {
    name: "ProcedureRecipe2022",
    setup() {
        let selectedRowKeys1 = ref()
        let selectedRowKeys2 = ref()
        let dataList: any = ref([])
        let dataList2: any = ref([])
        const total = ref(10);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            pagination.page = val
            doRefresh();
        }

        function change1(val: any) {
            pagination.pageSize = val
            doRefresh();
        }
        const headerShow = ref<boolean>(true)
        //查询方法
        function doRefresh() {
            pageData.pageLoading = true
            // updateGridState01()
            post({
                url: "/pdm/ProcessFormula/selectForm",
                data: {
                    page: page.value,
                    size: size.value,
                    deleteState: "0",
                    programNumber: pageData.programNumber
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        gridOption.value.setRowData(data.list);
                        total.value = data.total;
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([
            {
                title: "序号",
                key: "id",
                dataIndex: "id",
                width: 300
            },
            {
                title: "程序号",
                key: "programNumber",
                dataIndex: "programNumber",
                width: 300
            },
            {
                title: "程序名称",
                key: "programName",
                dataIndex: "programName",
                width: 300
            },
            {
                title: "程序类型",
                key: "programType",
                dataIndex: "programType",
                width: 300
            },
            {
                title: '操作',
                key: "id",
                slotName: 'act',
                width: 160,
                fixed: 'right'
            }
        ]);
        const tableColumns1 = useTableColumn([
            {
                title: '染色工序名称',
                key: 'dyeProcessName',
                dataIndex: 'dyeProcessName',
                width: 150,
                slotName: 'dyeProcessName',
            },
            {
                title: '呼料步骤',
                key: 'thickenerStep',
                dataIndex: 'thickenerStep',
                width: 150,
                slotName: 'thickenerStep',
            },
            {
                title: '物料编码',
                key: 'materialCode',
                dataIndex: 'materialCode',
                width: 150,
                slotName: 'materialCode',
            },
            {
                title: '物料名称',
                key: 'materialName',
                dataIndex: 'materialName',
                width: 150,
                slotName: 'materialName',
            },
            {
                title: '单位',
                key: 'unit',
                dataIndex: 'unit',
                width: 150,
                slotName: 'unit',
            },
            {
                title: '用料比例',
                key: 'materialRatio',
                dataIndex: 'materialRatio',
                width: 150,
                slotName: 'materialRatio',
            },
            {
                title: '浓度',
                key: 'concentration',
                dataIndex: 'concentration',
                width: 150,
                slotName: 'concentration',
            },
            {
                title: '浓度单位',
                key: 'concentrationUnit',
                dataIndex: 'concentrationUnit',
                width: 150,
                slotName: 'concentrationUnit',
            },
            {
                title: '总浓度最大限制(g/l)',
                key: 'maxLimit',
                dataIndex: 'maxLimit',
                width: 150,
                slotName: 'maxLimit',
            },
            {
                title: '操作步骤',
                key: 'operatingSteps',
                dataIndex: 'operatingSteps',
                width: 150,
                slotName: 'operatingSteps',
            },
            {
                title: '料桶',
                key: 'chargingBasket',
                dataIndex: 'chargingBasket',
                width: 150,
                slotName: 'chargingBasket',
            },
            {
                title: '投染系数',
                key: 'coefficient',
                dataIndex: 'coefficient',
                width: 150,
                slotName: 'coefficient',
            },
            {
                title: '输送方式',
                key: 'meansDelivery',
                dataIndex: 'meansDelivery',
                width: 150,
                slotName: 'meansDelivery',
            },
        ])
        let tc: any[] = tableColumns.map((o) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            // obj["width"] = 355
            if (o.slotName === 'act') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj["width"] = 105
                obj['cellRenderer'] = {
                    template: `<a-space>
                                   <el-button style="color:#165dff;" link @click="a">修改</el-button>
                                   <el-button style="color:#165dff;" link @click="a2">详情</el-button>
                               </a-space>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        const a2 = () => {
                            Details(props.params.data)
                        }
                        return {
                            a,
                            a2,
                        }
                    }

                }
            }

            return obj
        })



        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 60,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 60,
            maxWidth: 60,
            lockPosition: "left",
        }]
        tc = a.concat(tc)

        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            nameList: [],
            pageLoading: boolean,
            typeList: [],
            dropDownData1: any,
            rHeight: any,
            btnList: any[],
            isEdit: boolean,
            ProcessNameList: [],
            firmListsy: any[],
            bmListsy: any[],
            wlCodeList: any[],
            cxNameList: any[],
            dyeNameList: any[],
            programName: any,
            programType: any,
            wlNameList: any[],
            programNumber: any,
            unitList: any[],
            stepList: any[],
            programId: any,
            NumberList: any[],
            cxList: any[],
            cxIdList: any[],
        }>({
            nameList: [],
            showAdd: false,
            sideTitle: '新增程序配方2022',
            dropDownData: "",
            pageLoading: false,
            typeList: [],
            dropDownData1: "",
            rHeight: 0,
            btnList: [],
            isEdit: false,
            ProcessNameList: [],
            firmListsy: [],
            bmListsy: [],
            wlCodeList: [],
            cxNameList: [],
            dyeNameList: [],
            programName: "",
            programType: "",
            wlNameList: [],
            programNumber: "",
            unitList: [],
            stepList: [],
            programId: null,
            NumberList: [],
            cxList: [],
            cxIdList: [],
        });
        //下拉框得到焦点 程序号
        const focusSel = () => {
            selCxAll({ "programNumber": "", deleteState: 0 });
        }

        //下拉数据  程序号
        const options = ref<any>(pageData.cxNameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { programNumber: value, deleteState: 0 }
                loading.value = true;
                selCxAll(ob);
                options.value = pageData.cxNameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };
        //下拉框查询 程序号
        function selCxAll(val: any) {
            post({
                url: "/pdm/ProgramNumber/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.cxNameList = data;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        onMounted(() => {
            // 切换tap到本页面执行的方法
            emitter.on("ProcedureRecipe2022", () => {
                // selCxAll({});
                doRefresh();
            });
            pageData.rHeight = document.getElementsByClassName("arco-tabs-content")[0]?.clientHeight
            //弹出层的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight + 30;
            }
            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementsByClassName("arco-tabs-content")[0]?.clientHeight
                //弹出层的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight + 30;
                }
            })
        });

        //查询
        const selectHandler = () => {
            pagination.page = 1
            doRefresh();
        }
        const queryData = reactive({
            controlMachineCode: ""
        });
        const addHandler = () => {
            selectedRowKeys1.value = []
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                } else {
                    dataForm[key] = "";
                }
            }
            pageData.showAdd = true
            pageData.sideTitle = '新增程序配方2022'
        }
        const dataForm = reactive<BrandInfo>({
            "id": null,
            "remark": "",
            "createName": "",
            "createTime": "",
            "updateName": "",
            "updateTime": "",
            "deleteState": 0,
            "obsoleteState": "",
            "programNumber": "",
            "programType": "",
            "programName": "",
            "dyeProcessName": "",
            "thickenerStep": null,
            "materialCode": "",
            "materialName": "",
            "unit": "",
            "materialRatio": "0/0",
            "concentration": null,
            "concentrationUnit": "",
            "maxLimit": null,
            "operatingSteps": "",
            "chargingBasket": "",
            "coefficient": null,
            "meansDelivery": "",
            "stepName": "",
            "programId": '',
        })

        // 表格准备事件
        const gridOption = ref()
        const colState = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
            colState.value = params.columnApi
        }

        const formRef = ref<FormInstance>()
        const sideOk = () => {
            for (let i = 0; i < dataList.value.length; i++) {
                let o: any = dataList.value[i]
                if (o['dyeProcessName'] == '' || o['dyeProcessName'] == undefined) {
                    Message.warning({
                        content: '染色工序名称必填',
                        duration: 5000,
                    })
                    return
                }
            }
            if (dataList.value.length == 0) {
                Message.warning({
                    content: '请添加物料',
                    duration: 5000,
                })
                return
            }
            let condition = dataList.value.some((item: { materialCode: string }, index: number) => {
                if (index !== 0) {
                    return item.materialCode === dataList.value[0].materialCode
                }
            })
            if (dataList.value[0].materialCode != 0) {
                if (condition) {
                    Message.warning({
                        content: '不能添加同样的物料',
                        duration: 5000,
                    })
                    return
                }
            }
            formRef.value?.validate().then((err) => {
                if (!err) {
                    pageData.pageLoading = true;
                    if (pageData.sideTitle === "新增程序配方2022") {
                        post({
                            url: "/pdm/ProcessFormula/insert",
                            data: {
                                programNumber: dataForm.programNumber,
                                programType: dataForm.programType,
                                programName: dataForm.programName,
                                list: dataList.value
                            }
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                selectedRowKeys1.value = []
                                pageData.showAdd = false;
                                doRefresh()
                                Message.success({
                                    content: "新增成功",
                                    duration: 6000,
                                });
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 6000,
                                });
                            }
                        }).finally(() => {
                            pageData.pageLoading = false
                        })
                    } else {
                        dataList.value.forEach((item: any) => {
                            delete item.isTypeIds
                        })
                        post({
                            url: "/pdm/ProcessFormula/update",
                            data: {
                                programNumber: dataForm.programNumber,
                                programType: dataForm.programType,
                                programName: dataForm.programName,
                                id: dataForm.id,
                                list: dataList.value
                            }
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields()
                                pageData.showAdd = false;
                                selectedRowKeys1.value = []
                                doRefresh()
                                Message.success({
                                    content: res.message,
                                    duration: 6000,
                                });
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 6000,
                                });
                            }
                        }).finally(() => {
                            doRefresh();
                            pageData.pageLoading = false
                        })
                    }
                }
            });
        }
        const sideNo = () => {
            selectedRowKeys1.value = []
            dataList.value = []
            pageData.showAdd = false
        }
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选')
                return
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    pageData.pageLoading = true;
                    post({
                        url: '/pdm/ProcessFormula/delete',
                        data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 6000
                            })
                            pagination.page = 1
                            doRefresh()
                        } else {
                            Message.error({
                                content: '修改失败',
                                duration: 6000
                            })
                        }
                    }).finally(() => {
                        pageData.pageLoading = false
                    });
                }
            })
        }
        const editHandler = (record: any) => {
            //循环对象 赋值
            for (let key in record) {
                dataForm[key] = record[key]
            }
            //拿到此页面的详情
            post({
                url: '/pdm/ProcessFormula/select',
                data: {
                    programNumber: record.programNumber,
                    "deleteState": 0
                }
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    dataList.value = data
                    dataList.value.forEach((item: any) => {
                        item['isTypeIds'] = isTypeIds++
                    })
                } else {
                    Message.error({
                        content: '查询失败！',
                        duration: 5000,
                    })
                }
            })
            pageData.sideTitle = '修改程序配方2022'
            pageData.showAdd = true
        }
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })
        }

        //下拉框得到焦点 染色工序名称
        const focusSel1 = () => {
            selCxAll1({ "processName": "" });
        }

        //下拉数据 染色工序名称
        const options1 = ref<any>(pageData.dyeNameList);
        const loading1 = ref(false);
        const handleSearch1 = (value: any) => {
            if (value) {
                const ob = { processName: value, deleteState: 0 }
                loading1.value = true;
                selCxAll(ob);
                options1.value = pageData.dyeNameList;
                loading1.value = false;
            } else {
                options1.value = []
            }
        };
        //下拉框查询 染色工序名称
        function selCxAll1(val: any) {
            post({
                url: "/pdm/DyeProcess/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    let dataList: any = [];
                    data.forEach(function (o: any) {
                        dataList.push(o["processName"])
                    });
                    pageData.dyeNameList = dataList;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        // 下拉框  物料编码 
        const focusSel2 = () => {
            selCxAll2({ materialCode: '', auditState: 1 })
        }
        const options2 = ref<any>(pageData.wlCodeList);
        const loading2 = ref(false);
        const handleSearch2 = (value: any) => {
            if (value) {
                const ob = { materialName: value, auditState: 1 }
                loading2.value = true;
                selCxAll2(ob);
                options2.value = pageData.wlCodeList;
                loading2.value = false;
            } else {
                options2.value = []
            }
        }
        function selCxAll2(val: any) {
            post({
                url: '/dwPurchase/MaterialInfo/getFieldValue',
                data: val,
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.wlCodeList = data
                } else {
                    Message.error({
                        content: '查询失败！',
                        duration: 5000,
                    })
                }
            })
        }
        const handCode = (record: any) => {
            record.materialName = ''
            record.unit = ''
            post({
                url: 'dwPurchase/MaterialInfo/getList',
                data: {
                    materialCode: record.materialCode,
                },
            }).then((res: any) => {
                if (res.code == 200) {
                    record.materialName = res.data[0].materialName
                    record.unit = res.data[0].unit
                }
            })
        }

        // 下拉框  物料名称
        const focusSel2s = () => {
            selCxAll2s({ materialName: '', auditState: 1 })
        }
        const options2s = ref<any>(pageData.wlNameList);
        const loading2s = ref(false);
        const handleSearch2s = (value: any) => {
            if (value) {
                const ob = { materialName: value, auditState: 1 }
                loading2s.value = true;
                selCxAll2s(ob);
                options2s.value = pageData.wlNameList;
                loading2s.value = false;
            } else {
                options2s.value = []
            }
        }
        function selCxAll2s(val: any) {
            post({
                url: 'dwPurchase/MaterialInfo/getFieldValue',
                data: val,
            }).then(({ data, code, message }: any) => {
                if (code === 200) {
                    pageData.wlNameList = data;
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    })
                }
            })
        }
        const handName = (record: any) => {
            record.materialCode = ''
            record.unit = ''
            post({
                url: 'dwPurchase/MaterialInfo/getList',
                data: {
                    materialName: record.materialName,
                },
            }).then((res: any) => {
                if (res.code == 200) {
                    record.materialCode = res.data[0].materialCode
                    record.unit = res.data[0].unit
                }
            })
        }

        //下拉框得到焦点 浓度单位
        const focusSel3 = () => {
            selCxAll3({ "concentrationUnit": "", deleteState: 0 });
        }

        //下拉数据 浓度单位
        const options3 = ref<any>(pageData.unitList);
        const loading3 = ref(false);
        const handleSearch3 = (value: any) => {
            if (value) {
                const ob = { concentrationUnit: value, deleteState: 0 }
                loading3.value = true;
                selCxAll3(ob);
                options3.value = pageData.unitList;
                loading3.value = false;
            } else {
                options3.value = []
            }
        };
        //下拉框查询 浓度单位
        function selCxAll3(val: any) {
            post({
                url: "/pdm/ConcentrationUnit/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    let dataList: any = [];
                    data.forEach(function (o: any) {
                        dataList.push(o["concentrationUnit"])
                    });
                    pageData.unitList = dataList;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        //下拉框得到焦点 操作步骤
        const focusSel4 = () => {
            selCxAll4({ "stepName": "", deleteState: 0 });
        }

        //下拉数据 操作步骤
        const options4 = ref<any>(pageData.stepList);
        const loading4 = ref(false);
        const handleSearch4 = (value: any) => {
            if (value) {
                const ob = { stepName: value, deleteState: 0 }
                loading4.value = true;
                selCxAll4(ob);
                options4.value = pageData.stepList;
                loading4.value = false;
            } else {
                options4.value = []
            }
        };
        //下拉框查询 操作步骤
        function selCxAll4(val: any) {
            post({
                url: "/pdm/OperationStep/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    let dataList: any = [];
                    data.forEach(function (o: any) {
                        dataList.push(o["stepName"])
                    });
                    pageData.stepList = dataList;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        //下拉框得到焦点 新增里的程序号
        const focusSel5 = () => {
            selCxAll5({ "programNumber": "", deleteState: 0 });
        }

        //下拉数据 新增里的程序号
        const options5 = ref<any>(pageData.NumberList);
        const loading5 = ref(false);
        const handleSearch5 = (value: any) => {
            if (value) {
                const ob = { programNumber: value, deleteState: 0 }
                loading5.value = true;
                selCxAll5(ob);
                options5.value = pageData.NumberList;
                loading5.value = false;
            } else {
                options5.value = []
            }
        };
        //下拉框查询 新增里的程序号
        function selCxAll5(val: any) {
            post({
                url: "/pdm/ProgramNumber/select",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.NumberList = data;
                } else {
                }
            });
        }
        const cxChange = (val: any) => {
            pageData.programName = ""
            pageData.programType = ""
            post({
                url: '/pdm/ProgramNumber/select',
                data: {
                    programNumber: pageData.programNumber,
                }
            }).then((res: any) => {
                if (res.code == 200) {
                    if (val) {
                        pageData.programName = res.data[0].programName
                        pageData.programType = res.data[0].programType
                    }
                }
            })
        }

        //程序号带出名称和类型
        const cxmcFocus2 = () => {
            if (dataForm.programNumber != "" && dataForm.programNumber != null && dataForm.programNumber != undefined) {
                post({
                    url: "/pdm/ProgramNumber/select",
                    data: {
                        "programNumber": dataForm.programNumber,
                    }
                })
                    .then(({ data, code }: any) => {
                        if (code === 200) {
                            pageData.cxList = data
                        }
                    })
            }
        }
        //当程序号为空时，名称和类型也为空
        const cxChange2 = (val: any) => {
            if (dataForm.programNumber == '') {
                pageData.cxList = []
                return
            } else {
                pageData.cxList.forEach((item: any) => {
                    if (item.programNumber == val) {
                        dataForm.programName = item.programName
                    }
                })
            }
        }
        const cxClick2 = () => {
            if (dataForm.programNumber == '') {
                pageData.cxList = []
                Message.error('请先选择程序号！')
                return
            }
        }
        //程序号直接带出名称类型
        const numChange = (val: any) => {
            if (dataForm.programNumber == "") {
                dataForm.programType = ""
                dataForm.programName = ""
                return
            }
            let list = pageData.NumberList.filter(function (o: any) {
                return o["programNumber"] == val
            })
            dataForm.programName = list[0]["programName"]
            dataForm.programType = list[0]["programType"]
        }

        const handleChange = (_data: any) => {
            table.handleSuccess(_data);
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            width: 373
        }

        //下拉框得到焦点 程序号
        const focusSel7 = () => {
            selCxAll7({ "programNumber": "", deleteState: 0 });
        }

        //下拉数据 程序号
        const options7 = ref<any>(pageData.cxIdList);
        const loading7 = ref(false);
        const handleSearch7 = (value: any) => {
            if (value) {
                const ob = { programNumber: value, deleteState: 0 }
                loading7.value = true;
                selCxAll7(ob);
                options7.value = pageData.cxIdList;
                loading7.value = false;
            } else {
                options7.value = []
            }
        };
        //下拉框查询 程序号
        function selCxAll7(val: any) {
            post({
                url: "pdm/ProcessFormula/selectProgramNumber",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.cxIdList = data.list;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        const pagingList1: any = ref(pagingList)
        const localeText1: any = ref(localeText)
        const huiche = () => {
            doRefresh();
        }

        let isTypeIds = 0
        const addyeing = () => {
            dataList.value.push({
                dyeProcessName: '',
                thickenerStep: 0,
                materialCode: '',
                materialName: '',
                unit: '',
                materialRatio: '0/0',
                concentration: 0,
                concentrationUnit: '',
                maxLimit: 0,
                operatingSteps: '',
                chargingBasket: '',
                coefficient: 0,
                meansDelivery: '',
                isTypeIds: isTypeIds++,
            })
        }
        const deldyeling = () => {
            if (selectedRowKeys1.value.length == 0) {
                Message.error('请选择要删除的数据')
                return
            }
            if (selectedRowKeys1.value.length > 1) {
                selectedRowKeys1.value.forEach((item: any, index: any) => {
                    dataList.value.forEach((items: any, indexs: any) => {
                        if (item == items.isTypeIds) {
                            dataList.value.splice(indexs, 1)
                        }
                    })
                })
                if (selectedRowKeys1.value.length > dataList.value.length) {
                    selectedRowKeys1.value = []
                }
            } else {
                dataList.value.some((item: any, index: any) => {
                    if (selectedRowKeys1.value == item.isTypeIds) {
                        dataList.value.splice(index, 1)
                        selectedRowKeys1.value = []
                    }
                })
            }
        }
        let DetailList: any = ref([])
        const visible1 = ref(false)
        const Details = (record: any) => {
            //拿到此页面的详情
            post({
                url: '/pdm/ProcessFormula/select',
                data: {
                    programNumber: record.programNumber,
                    "deleteState": 0
                }
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    DetailList.value = data
                } else {
                    Message.error({
                        content: '查询失败！',
                        duration: 5000,
                    })
                }
            })
            visible1.value = true
        }

        //导出
        const exports = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选')
                return
            } else {
                //将表头拼接出来
                let head =
                    '<th>序号</th><th>程序号</th><th>程序名称</th><th>程序类型</th>'
                //拿到当前表格数据与勾选的行做筛选
                let nowRow = table.dataList.filter(function (o) {
                    return (gridOption.value.getSelectedRows().map((o: any) => { return o.id }).indexOf(o['id']) !== -1)
                })
                let body = ''
                nowRow.forEach(function (o) {
                    body += '<tr><td>' + o['id'] + '</td>'
                    body += '<td>' + o['programNumber'] + '</td>'
                    body += '<td>' + o['programName'] + '</td>'
                    body += '<td>' + o['programType'] + '</td>'
                    body += '</tr>'
                })
                tableToXlsx(head, '程序配方2022定义', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

            const a = document.createElement('a')
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
            a.download = filename
            a.click()
            document.removeChild(a)
        }


        //复制
        const visible = ref(false);
        function copyPro() {
            visible.value = true
            dataForm.programId = ''

        }

        function handleSave() {
            post({
                url: "pdm/ProcessFormula/select",
                data: {
                    programNumber: dataForm.programId.split('——')[0],
                    deleteState: 0
                }
            }).then(({ data, code, message }: any) => {
                if (code === 200) {
                    data.forEach((o: any) => {
                        o.uid = null
                        o.id = null
                        o.programNumberId = null
                        o.programName = ''
                        o.programNumber = ''
                        o.programType = ''
                        o.isTypeIds = isTypeIds++
                    })
                    dataList.value = []
                    dataList.value = data
                    visible.value = false
                    console.log(dataList.value);
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }
            });
        }

        const copyCode = () => {
            dataForm.programId = dataForm.programId.split('——')[0]
        }

        const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('ProcedureRecipe202201', gridOption, colState, tc)
        const onColumnMoved = () => {
            saveGridState01()
        }
        const onColumnResized = () => {
            saveGridState01()
        }
        return {
            copyPro,
            handleSave,
            exports,
            saveOrUpdateGridState01,
            saveGridState01,
            updateGridState01,
            onColumnMoved,
            onColumnResized,
            colState,
            sideNo,
            visible1,
            DetailList,
            Details,
            addyeing,
            deldyeling,
            dataList,
            dataList2,
            selectedRowKeys1,
            selectedRowKeys2,
            tableColumns1,
            pagingList1,
            huiche,
            localeText1,
            copyCode,
            focusSel7,
            options7,
            loading7,
            handleSearch7,
            visible,
            numChange,
            cxmcFocus2,
            cxClick2,
            cxChange2,
            focusSel5,
            options5,
            loading5,
            handleSearch5,
            focusSel4,
            options4,
            loading4,
            handleSearch4,
            focusSel3,
            options3,
            loading3,
            handleSearch3,
            cxChange,
            focusSel2,
            options2,
            loading2,
            options2s,
            loading2s,
            handleSearch2,
            handCode,
            handName,
            focusSel2s,
            handleSearch2s,
            selCxAll2s,
            editHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            selectHandler,
            isChiese,
            options,
            loading,
            handleSearch,
            focusSel,
            options1,
            loading1,
            handleSearch1,
            focusSel1,
            headerShow,
            handleChange,
            PageSize,
            change1,
            defaultColDef,
            tc,
            gridOption,
            gridReady,
            total,
            page,
            size,
        };
    },
    components: { Toolbar, PageTabelLayout,  }
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.input-demo bacClass {
    border-right: 1px solid #dde2eb;
}

.input-demo {
    border-right: 1px solid #dde2eb;
}
</style>